package com.wangzhixuan.controller;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import java.util.UUID;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wangzhixuan.commons.result.PageInfo;
import com.wangzhixuan.commons.utils.StringUtils;
import com.wangzhixuan.model.Craftsman;
import com.wangzhixuan.service.ICraftsmanService;
import com.wangzhixuan.commons.base.BaseController;

/**
 * <p>
 * 用户角色 前端控制器
 * </p>
 *
 * @author zhixuan.wang
 * @since 2017-06-24
 */
@Controller
@RequestMapping("/craftsman")
public class CraftsmanController extends BaseController {

    @Autowired private ICraftsmanService craftsmanService;
    
    @InitBinder  
    public void initBinder(WebDataBinder binder) {  
    	SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
	    dateFormat1.setLenient(false);  
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat1, true)); 
	    
	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
	    dateFormat.setLenient(false);  
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   //true:允许输入空值，false:不能为空值
    }
    
    @GetMapping("/manager")
    public String manager() {
        return "admin/craftsman/craftsmanList";
    }
    
    @PostMapping("/dataGrid")
    @ResponseBody
    public PageInfo dataGrid(Craftsman craftsman, Integer page, Integer rows, String sort,String order) {
        PageInfo pageInfo = new PageInfo(page, rows, sort, order);
        EntityWrapper<Craftsman> ew = new EntityWrapper<Craftsman>();
	    if(StringUtils.isNotBlank(craftsman.getManBrand())){
	        ew.like("man_brand", craftsman.getManBrand());
	    }
	    
	    if(StringUtils.isNotBlank(craftsman.getManCompany())){
	        ew.like("man_company", craftsman.getManCompany());
	    }
	    
	    if(StringUtils.isNotBlank(craftsman.getManName())){
	        ew.like("man_name", craftsman.getManName());
	    }
		ew.orderBy("id", false);
        Page<Craftsman> pages = getPage(pageInfo);
        pages = craftsmanService.selectPage(pages, ew);
        pageInfo.setRows(pages.getRecords());
        pageInfo.setTotal(pages.getTotal());
        return pageInfo;
    }
    
    /**
     * 添加页面
     * @return
     */
    @GetMapping("/addPage")
    public String addPage() {
        return "admin/craftsman/craftsmanAdd";
    }
    
    /**
     * 添加
     * @param 
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public Object add(@RequestParam MultipartFile[] myfiles, HttpServletRequest request, @Valid Craftsman craftsman) {
    	try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			String pathRoot = request.getSession().getServletContext().getRealPath("");  
			// 头像
			String path="";
			MultipartFile file = multipartRequest.getFile("pic_manPhoto");
			if(file != null && file.getSize()>0) {
				String uuid = UUID.randomUUID().toString().replaceAll("-","");  
				//获得文件类型（可以判断如果不是图片，禁止上传）  
	            String contentType=file.getContentType();  
	            //获得文件后缀名称  
	            String imageName=contentType.substring(contentType.indexOf("/")+1);  
	            path="/upload/images/"+uuid+"."+imageName;  
	            file.transferTo(new File(pathRoot+path));  				  
				craftsman.setManPhoto(path);
			}
			
			// 公司logo
			MultipartFile file2 = multipartRequest.getFile("pic_manCompanyLogo");
			String path2="";
			if(file2 != null && file2.getSize()>0) {
				String uuid = UUID.randomUUID().toString().replaceAll("-","");  
				//获得文件类型（可以判断如果不是图片，禁止上传）  
	            String contentType=file2.getContentType();  
	            //获得文件后缀名称  
	            String imageName=contentType.substring(contentType.indexOf("/")+1);  
	            path2="/upload/images/"+uuid+"."+imageName;  
	            file2.transferTo(new File(pathRoot+path2));  				  
				craftsman.setManCompanyLogo(path2);
			}
			
			// 品牌logo
			MultipartFile file3 = multipartRequest.getFile("pic_manBrandLogo");
			String path3="";
			if(file3 != null && file3.getSize()>0) {
				String uuid = UUID.randomUUID().toString().replaceAll("-","");  
				//获得文件类型（可以判断如果不是图片，禁止上传）  
	            String contentType=file3.getContentType();  
	            //获得文件后缀名称  
	            String imageName=contentType.substring(contentType.indexOf("/")+1);  
	            path3="/upload/images/"+uuid+"."+imageName;  
	            file3.transferTo(new File(pathRoot+path3));  				  
				craftsman.setManBrandLogo(path3);
			}
			
			boolean b = craftsmanService.insert(craftsman);
	        if (b) {
	            return renderSuccess("添加成功！");
	        } else {
	            return renderError("添加失败！");
	        }
	        
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return renderError("添加失败！");
    }
    
    /**
     * 删除
     * @param id
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    public Object delete(Long id) {
        Craftsman craftsman = new Craftsman();
        craftsman.setId(id);
        boolean b = craftsmanService.deleteById(craftsman);
        if (b) {
            return renderSuccess("删除成功！");
        } else {
            return renderError("删除失败！");
        }
    }
    
    /**
     * 编辑
     * @param model
     * @param id
     * @return
     */
    @GetMapping("/editPage")
    public String editPage(Model model, Long id) {
        Craftsman craftsman = craftsmanService.selectById(id);
        model.addAttribute("craftsman", craftsman);
        return "admin/craftsman/craftsmanEdit";
    }
    /**
     * 编辑
     * @param model
     * @param id
     * @return
     */
    @GetMapping("/viewPage")
    public String viewPage(Model model, Long id) {
        Craftsman craftsman = craftsmanService.selectById(id);
        model.addAttribute("craftsman", craftsman);
        return "admin/craftsman/craftsmanView";
    }
    /**
     * 编辑
     * @param 
     * @return
     */
    @PostMapping("/edit")
    @ResponseBody
    public Object edit(@RequestParam MultipartFile[] myfiles, HttpServletRequest request, @Valid Craftsman craftsman) {
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			String pathRoot = request.getSession().getServletContext().getRealPath("");  
			// 头像
			String path="";
			MultipartFile file = multipartRequest.getFile("pic_manPhoto");
			if(file != null && file.getSize()>0) {
				String uuid = UUID.randomUUID().toString().replaceAll("-","");  
				//获得文件类型（可以判断如果不是图片，禁止上传）  
	            String contentType=file.getContentType();  
	            //获得文件后缀名称  
	            String imageName=contentType.substring(contentType.indexOf("/")+1);  
	            path="/upload/images/"+uuid+"."+imageName;  
	            file.transferTo(new File(pathRoot+path));  				  
				craftsman.setManPhoto(path);
			}
			
			// 公司logo
			MultipartFile file2 = multipartRequest.getFile("pic_manCompanyLogo");
			String path2="";
			if(file2 != null && file2.getSize()>0) {
				String uuid = UUID.randomUUID().toString().replaceAll("-","");  
				//获得文件类型（可以判断如果不是图片，禁止上传）  
	            String contentType=file2.getContentType();  
	            //获得文件后缀名称  
	            String imageName=contentType.substring(contentType.indexOf("/")+1);  
	            path2="/upload/images/"+uuid+"."+imageName;  
	            file2.transferTo(new File(pathRoot+path2));  				  
				craftsman.setManCompanyLogo(path2);
			}
			
			// 品牌logo
			MultipartFile file3 = multipartRequest.getFile("pic_manBrandLogo");
			String path3="";
			if(file3 != null && file3.getSize()>0) {
				String uuid = UUID.randomUUID().toString().replaceAll("-","");  
				//获得文件类型（可以判断如果不是图片，禁止上传）  
	            String contentType=file3.getContentType();  
	            //获得文件后缀名称  
	            String imageName=contentType.substring(contentType.indexOf("/")+1);  
	            path3="/upload/images/"+uuid+"."+imageName;  
	            file3.transferTo(new File(pathRoot+path3));  				  
				craftsman.setManBrandLogo(path3);
			}
			
		    boolean b = craftsmanService.updateById(craftsman);
	        if (b) {
	            return renderSuccess("编辑成功！");
	        } else {
	            return renderError("编辑失败！");
	        }
	        
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return renderError("编辑失败！");
    }
}
